#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>

int main()
{
    int pipefd[2]={0};    
    //pipefd[0]为以读的方式打开管道文件的文件描述符
    //pipefd[1]为以写的方式打开管道文件的文件描述符
    if(pipe(pipefd)!=0)
    {
        exit(1);
    }
    pid_t id = fork();
    //子进程读，父进程写
    if(id==0)
    {
        //子进程关闭读端
        close(pipefd[0]);
        //子进程写
        int cnt=5;
        char msg[]="hello world\n";
        while(cnt--)
        {
            write(pipefd[1],msg,strlen(msg));
            printf("写入：%s\n",msg);
        } 
        exit(1);
    }
    else
    {
        //父进程关闭写端
        close(pipefd[1]);
        //子进程读
        int cnt=5;
        char mag[124];
        while(cnt--)
        {
            read(pipefd[0],mag,123);
            printf("读出：%s\n",mag);
        } 
        //父进程回收子进程
        int status=0;
        waitpid(id,&status,0);
        printf("hello pipe\n");
    }
    return 0;

}